package cn.com.chengmandian.bike.service.impl;

import cn.com.chengmandian.bike.mapper.EbRideModifyMapper;
import cn.com.chengmandian.bike.model.EbRideModify;
import cn.com.chengmandian.bike.model.EbRideOrder;
import cn.com.chengmandian.bike.service.IEbRideModifyService;
import cn.com.chengmandian.core.common.constants.CommonConstant;
import cn.com.chengmandian.core.web.pojo.AgentUser;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * <p>
 * 电单车运营-骑行订单调价 服务实现类
 * </p>
 *
 * @author AutoGenerator
 * @since 2022-11-14
 */
@Service
public class EbRideModifyServiceImpl extends ServiceImpl<EbRideModifyMapper, EbRideModify> implements IEbRideModifyService {

    @Override
    public void createRecord(AgentUser agentUser, EbRideOrder rideOrder, Integer moneyType, BigDecimal oriMoney, BigDecimal updateMoney, String remark) {
        EbRideModify oldRideModify = this.getOne(new LambdaQueryWrapper<EbRideModify>()
                .eq(EbRideModify::getOrderId,rideOrder.getId())
                .eq(EbRideModify::getMoneyType, moneyType)
                .orderByAsc(EbRideModify::getCreateTime)
                .last("limit 0,1"));
        EbRideModify ebRideModify = new EbRideModify();
        ebRideModify.setAreaId(rideOrder.getAreaId());
        ebRideModify.setOrderId(rideOrder.getId());
        ebRideModify.setCreateUser(agentUser.getId());
        ebRideModify.setCreateName(agentUser.getName());
        ebRideModify.setCreateTime(DateUtil.date());
        ebRideModify.setNote(remark);
        ebRideModify.setMoneyType(moneyType);
        ebRideModify.setIsLast(CommonConstant.ONE);
        if(ObjectUtil.isNotNull(oldRideModify)){
            ebRideModify.setPreMoney(oldRideModify.getPreMoney());
            ebRideModify.setMoney(updateMoney);
            BigDecimal diffMoney = updateMoney.subtract(oldRideModify.getPreMoney());
            ebRideModify.setDiffMoney(diffMoney);
        }else{
            ebRideModify.setPreMoney(oriMoney);
            ebRideModify.setMoney(updateMoney);
            BigDecimal diffMoney = updateMoney.subtract(oriMoney);
            ebRideModify.setDiffMoney(diffMoney);
        }
        if(ebRideModify.getDiffMoney() == null || ebRideModify.getDiffMoney().compareTo(BigDecimal.ZERO) == 0){
            return;
        }
        this.update(new LambdaUpdateWrapper<EbRideModify>()
                .set(EbRideModify::getIsLast,CommonConstant.ZERO)
                .eq(EbRideModify::getOrderId,rideOrder.getId()));
        this.save(ebRideModify);
    }
}
